package com.hebeu.xwl.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hebeu.xwl.dao.LogDao;
import com.hebeu.xwl.dto.AdminDto;
import com.hebeu.xwl.dto.UserDto;
import com.hebeu.xwl.pojo.*;
import com.hebeu.xwl.service.AdminService;
import com.hebeu.xwl.service.UserService;
import com.hebeu.xwl.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;



@RequestMapping("/Admin")
@Slf4j
@SaCheckLogin
@SaCheckRole("admin")
@RestController
public class AdminController{
    @Autowired
    private AdminService adminService;
    @Autowired
    private UserService userService;
    @Autowired
    private LogDao logDao;
    /*
    * 登录
    * */
    @SaIgnore
    @PostMapping("/login")
    public Result<Admin> login(@RequestBody LoginBean loginBean){
        if(loginBean.getPassword()==null||loginBean.getName()==null){
            return new Result(1,"请检查是否有未填写信息");
        }
        Admin adminTrue = adminService.findByUsername(loginBean.getName());
        //3、如果没有查询到则返回登录失败结果
        if(adminTrue  == null){
            return new Result(1,"登陆失败");
        }
        AdminSalt adminSalt = adminService.findAdminSalt(adminTrue.getId());
        String password = MD5Utils.getSaltMD5(loginBean.getPassword(),adminSalt.getSalt());
        //4、密码比对，如果不一致则返回登录失败结果
        if(!password.equals(adminTrue .getPassword())){
            return  new Result(1,"登陆失败");
        }
        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(adminTrue .getStatus() == 0){
            return new Result(1,"账号已禁用");
        }
        //6、登录成功，返回token
        Map<String,String> map = new HashMap<String,String>();
        // 使用sa-token直接登录
        StpUtil.login(adminTrue.getId() +"%"+"Admin");
        return new Result(0,map,"Success");
    }
    /**
     * 员工退出
     * @param
     * @return
     */
    @PostMapping("/logout")
    public Result logout(){
        //框架登出，反正也没什么用
        StpUtil.logout();
        return new Result(0,"Success");
    }
    //修改密码
    @PostMapping("/changePasswd")
    @SaCheckRole("super-admin")
    public Result changePasswd(HttpServletRequest request,@RequestParam Integer adminId,@RequestParam String pwd){
        if(pwd==null){
            return new Result(1,"请检查是否有未填写信息");
        }
        //获取用户ID
        Admin adminTrue = adminService.findById(String.valueOf(adminId));
        AdminSalt adminSalt = adminService.findAdminSalt(adminTrue.getId());
        pwd = MD5Utils.getSaltMD5(pwd,adminSalt.getSalt());
        adminTrue.setPassword(pwd);
        adminService.UpdatePassword(adminTrue);
        return new Result(0,"修改管理员成功");
    }

    //更新用户状态
    @PostMapping("/status")
    public Result setStatus(@RequestParam Integer id,Integer status){
        Admin adminTrue = adminService.findById(String.valueOf(id));
        if(adminTrue.getId()==1)
        {
            return new Result(1,"不允许修改超级管理员");
        }
        int mystatus = status > 0 ?1:0;
        adminTrue.setStatus(mystatus);
        adminService.UpdateStatus(adminTrue);
        return new Result(0,"修改管理员状态成功");
    }

    /**
     * 新增管理员
     * @param
     * @return
     */
    @PostMapping("/add")
    @SaCheckRole("super-admin")
    public Result add(@RequestBody LoginBean newadmin){
        if(newadmin.getName()==null||newadmin.getPassword()==null){
            return new Result(1,"请检查是否有未填写信息");
        }
        Admin admin = new Admin();
        admin.setUsername(newadmin.getName());
        String salt = MD5Utils.getSalt();
        String saltMD5 = MD5Utils.getSaltMD5(newadmin.getPassword(), salt);
        admin.setPassword(saltMD5);
        admin.setStatus(1);
        //设置初始密码123456，需要进行md5加密处理
        if(adminService.insertAdmin(admin,salt)){
            return new Result(0,"新增成功");
        }
        return new Result(1,"新增失败");
    }
    //删除管理员
    @PostMapping("/deleteAdmin")
    @SaCheckRole("super-admin")
    public Result delete(@RequestParam Integer id){
        if(!adminService.deleteAdmin(id)){
            return new Result(1,"该用户不存在");
        }else{
            return new Result(0,"Success");
        }
    }
    //查询所有用户返回给前端
    @PostMapping("/UserPage")
    @SaCheckLogin
    public Result findAllUser(@RequestParam Integer page,Integer pageSize){
        Page<User> pageInfo = new Page(page,pageSize);
        Page<UserDto> UserDtoPage = new Page<>();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderBy(true,true,User::getUserId);
        userService.page(pageInfo,queryWrapper);
        BeanUtils.copyProperties(pageInfo,UserDtoPage,"records");

        List<User> records = pageInfo.getRecords();
        List<UserDto> list = records.stream().map((item) -> {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(item, userDto);
            return userDto;
        }).collect(Collectors.toList());
        UserDtoPage.setRecords(list);
        return  new Result(0,UserDtoPage,"Success");
    }
    //分页查询管理员
    @PostMapping("/AdminPage")
    @SaCheckLogin
    @SaCheckRole("super-admin")
    public Result findAllAdmin(Integer page,Integer pageSize){
        Page<Admin> pageInfo = new Page(page,pageSize);
        Page<AdminDto> adminPage = new Page<>();
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderBy(true,true,Admin::getId);
        adminService.page(pageInfo,queryWrapper);
        BeanUtils.copyProperties(pageInfo,adminPage,"records");
        List<Admin> records = pageInfo.getRecords();
        List<AdminDto> list = records.stream().map((item) -> {
            AdminDto adminDto = new AdminDto();
            BeanUtils.copyProperties(item, adminDto);
            return adminDto;
        }).collect(Collectors.toList());
        adminPage.setRecords(list);
        return  new Result(0,adminPage,"Success");
    }
    //删除用户 - 普通管理即可
    @PostMapping("/deleteUser")
    public Result deleteUser(@RequestParam int userId){
        int i = userService.deleteById(userId);
        if(i==0){
            return new Result(1,"该用户不存在");
        }else{
            return new Result(0,"Success");
        }
    }
    //日志
    @PostMapping("/LogPage")
    public Result findLog(@RequestParam Integer page, Integer pageSize){
        //构造分页构造器对象
        Page<Log> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Log> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Log::getLogId);
        logDao.selectPage(pageInfo,queryWrapper);
        List<Log> records = pageInfo.getRecords();
        return new Result(0,records,"Success");
    }



}
